

BUILD = 20;
shrunk = false;
function gadget_init(){
	// handles resizing event
	window.onresize = function(event) {
		resize_window()
	}
};

function resize_window( force ){
	width =$("body").innerWidth();
		
	if( width  < 290 && (shrunk == false || force == true)){
		$(".front #lightning_percent").hide();
		$(".front #image_mask").hide();
		$(".front #image").hide();
		$(".front #timer").hide();
		$(".front #price_titles").css("right", "6px");				
		$(".front #bar").css("right", "6px");				
		$(".front #lightning_price").css("right", "11px");				
		$(".front #lightning_title").css("right", "72px");
		
		shrunk = true;
	}else if( width >= 290 && (shrunk == true|| force == true)){
		$(".front #lightning_percent").show();
		$(".front #image_mask").show();
		$(".front #image").show();
		$(".front #timer").show();				
		$(".front #price_titles").css("right", "110px");
		$(".front #bar").css("right", "110px");				
		$(".front #lightning_price").css("right", "115px");				
		$(".front #lightning_title").css("right", "176px");				
		shrunk = false;
	}
}

function link( link ){
	if( window.widget)
		widget.openURL( link );
	else
		window.open(link);
	
}
jQuery.fn.toFront = function() {
  return this.each(function(){
    
		// set the current front frame to remove and bring to front		
		remove_this = jQuery(".front").css("z-index", "999");
		// display the new frame 
		jQuery(this).addClass("front")
		resize_window(true);
		jQuery(this).show();
		// fade out remove frame
		remove_this.fadeOut("fast", function(){
			jQuery(this).remove();
		})
		
  });
};

function Lightning(){
	
	this.uniq_id = (new Date ()).getTime() + 2000000000000; // uniq _id
	
	this.object_name = "Lightning";
	
	this.data = null;
	
	this.deal_id = null;
	this.asin = null;
	this.expires = null;
	
	this.deal_state = null; 
	this.percentage_sold = null; 
	
	this.claimed_timer = null;
	this.timer = null;
	this.timer_suffix = '';
	this.timer_interval = 1000;
	
	this.minimized = false;
	
	this.connection_timeout = 1;
		
}

Lightning.prototype.stopTimers = function(){
	
	this.minimized = true;
	
	clearInterval(this.timer)
	this.timer = null;
	
	
	clearInterval(this.claimed_timer)
	this.claimed_timer = null;
}

Lightning.prototype.startTimers = function(){
	// Clear any timers just in case
	clearInterval(this.timer)
	this.timer = null;
	
	this.timer_interval = 1000;
	timer_complete = lightning.update_timer();
	
	// If timer is not complete and a deal is still active, restart claimed timer
	if( this.minimized && !timer_complete && this.deal_id ){	
		clearInterval(this.claimed_timer)
		this.claimed_timer = null;
		
		this.claimed_timer =  setInterval("lightning.update_claimed();", 30000);
		lightning.update_claimed();

	}
	if(!timer_complete)
		this.timer =  setInterval("lightning.update_timer();", this.timer_interval);
	
	this.minimized = false;
}


//  Problem getting data - or with network connection.  Show error screen and attempt reconnect.
Lightning.prototype.connection_error = function(){

	wait_time = Math.round(Math.log(this.connection_timeout) + (5 * this.connection_timeout)) * 1000;
	
	if( wait_time > 3600000)
		wait_time = 360000;
	
	
	this.expires = (new Date).getTime() + wait_time;
	
	this.connection_timeout += 1;
	
	data = {"content": "Problem contacting server.<br/> Trying again in <span id='timer'>..</span>."}
	$('#front_loading').render(data, {preserve_template : true}).toFront();

	this.timer_suffix = '';
	if( this.timer != null ){
		clearInterval(this.timer);
		this.timer = null;
	}
	lightning.update_timer();
	this.timer =  setInterval("lightning.update_timer();", this.timer_interval);
}

// Called on timer end.  Wait 4 seconds for server to grab deal.  Then randomly between 0-15 seconds, contact the server.
Lightning.prototype.wait_and_load = function(){
	
	// Timer over - clear deal_id, and claimed timer
	this.deal_id = null;
	clearInterval( this.claimed_timer );
	this.claimed_timer = null;
	
	
	data = {"content": "Loading new deals..."};
	$('#front_loading').render(data, {preserve_template : true}).toFront();
	
	
	setTimeout("lightning.load()", 3000 + Math.random()*7000);
}


Lightning.prototype.load = function(){
		
	self = this;
	// Get the latest deal/status from echodot servers
	$.ajax({
		url:"http://update.echodot.com/lightning/", 
		//url:"http://127.0.0.1/~scum/echodot/update/lightning/",
		dataType: 'json',
		cache:false,
		data:{ build:BUILD, "id":self.uniq_id},
		
		success:function(data){
			//console.info(data);
			// do a basic check to see if data is JSON
			if( typeof(data) != "object"){
				self.connection_error();
				return false;
			}
			
			if( data.type == "update"){
				//return false;
			}else if( data.type == "shout_out"){
				//return false;
			}
			else if( data.type == "empty") {
				self.expires = new Date(data.ttwt * 1000);

				// stop updating claimed.
				clearInterval(self.claimed_timer);
				self.claimed_timer = null;
				
				self.timer_suffix = " to next deal.";
				data = {"content": "No lightning deals currently active."}
				$('#front_loading').render(data, {preserve_template : true}).toFront();
				
				if( self.timer != null ){
					clearInterval(self.timer);
					self.timer = null;
				}
				
				lightning.update_timer();
				self.timer =  setInterval("lightning.update_timer();", self.timer_interval);

				return false;
			}
			
			start_time = new Date(data.start_time * 1000);
			// If a deal has not yet started
			if( start_time > new Date() ){
				
				self.expires = start_time;					

				// stop updating claimed.
				clearInterval(self.claimed_timer);
				self.claimed_timer = null;
				
				self.timer_suffix = ' to next deal...';
				data = {"content": "No lightning deals currently active."}
				$('#front_loading').render(data, {preserve_template : true}).toFront();
				
				if( self.timer != null ){
					clearInterval(self.timer);
					self.timer = null;
				}
				self.timer =  setInterval("lightning.update_timer();", self.timer_interval);

				return false;
			}
			
			// Continue
			if(data.asin == '' && data.title == ''){
				self.connection_timeout += 1;
				self.connection_error();
				return false;
			}
			
			self.connection_timeout = 1;  // reset timeout count to 1
			
			

				
			// Display deal
			self.deal_id = data.deal_id;
			self.asin = data.asin;
			self.expires = new Date(data.end_time * 1000);
			
			data.rating = Math.round(data.rating * 2) / 2;  // round to nearest .5
			
			if( data.amazon_price > 0)
				data.gold_box_discount = Math.round((data.amazon_price - data.gold_box_price)*100)/100;
			else{
					data.gold_box_discount = Math.round((data.list_price - data.gold_box_price)*100)/100;
					data.amazon_price = data.list_price;
			}
			
			
			data.gold_box_percent =  Math.round( (1-(data.gold_box_price / data.list_price)) * 100 );
			
			data.gold_box_discount = data.gold_box_discount.toFixed(2);
			
			self.data = data;
			
			// Clear gray out from previous deal if needed
			$(".front .lightning_line").removeClass("gray_out");
			
			$('#front_template').render(data, {preserve_template : true}).toFront();
			
			
			$('.front #image').css("background-image", "url(" + data.image + ")");
			$('.front #image').css({
				"-moz-background-size": "contain",
				"-webkit-background-size": "contain",			
				"background-size": "contain",
			});
			
			
			if( data.amazon_price == 0 )
				$('.front #amazon_price').hide();
				
			if(!data.rating)
				$('.front #rating').hide();
			
						
			lightning.update_claimed();
			self.claimed_timer =  setInterval("lightning.update_claimed();", 30000);
						
		},
		error: function(){
			self.connection_timeout += 1;
			self.connection_error();
			return false;

		}
	});


}



// Calls amazon and updates claimed amount.  Should be repeated every 30 seconds while dashboard is open.
Lightning.prototype.update_claimed = function(){
	
	self = this;
	
	data_key = '{"requestMetadata":{"marketplaceID":"1"},"dealIDs":["'+this.deal_id+'"]}';
	data_dict = {}
	data_dict[data_key] = '';
	
	$.ajax({
		type : "POST",
		url:"http://www.amazon.com/xa/goldbox/GetDealStatus", 
		data: data_key,
		dataType: 'json',
		processData:false,
		success:function(data){
			//console.info(data);
			// do a basic check to see if data is JSON
			
			self.deal_state = data.getDealState;
			self.percentage_sold = data.dealStatus[self.deal_id].percentClaimed;
						
			if( data.dealStatus[self.deal_id].msToEnd <= 0)
				self.deal_state = "Expired";
			else if(self.percentage_sold < 100)
				self.deal_state = "Available"
			else if(self.percentage_sold == 100)
				self.deal_state = "Sold Out";
			
			self.handle_deal_state( );

			
		},
		error: function(){
			// setTimeout("lightning.update_claimed", 60000);
			//console.info("Error connecting to amazon for claimed info.  Trying again in 30.");
		}
	});
}

// Count down to lightning expiration and handle updates.
// Interval function set to this.timer
// Returns true if timer is complete
Lightning.prototype.update_timer = function(){
	current_time = new Date();
	remaining_ms = this.expires - current_time;
	
	// Don't let timestamp go negative
	if( remaining_ms <=0 )
		remaining_ms = 0;
	
	remaining_seconds = Math.floor(remaining_ms/1000)
			
	seconds = Math.floor(remaining_seconds % 60)	
	remaining_minutes = Math.floor( remaining_seconds / 60);
	minutes = Math.floor(remaining_minutes % 60)
	remaining_hours = Math.floor( remaining_minutes / 60);
	hours = Math.floor(remaining_hours % 24)

	// construct string
	time_string = '';
	if( hours > 0){
		time_string += hours + "hr ";
		if( minutes > 0)
			time_string += minutes + "min";	
	}else if (minutes >= 10)
		time_string += minutes + " minutes";
	else if( minutes >= 1){
		time_string += minutes + " min ";
		time_string += seconds + " secs";	
	}else
		time_string += seconds + " seconds";
	
	$('.front #timer').html( time_string + this.timer_suffix)
	
	// stop timer and get a new deal
	if( remaining_ms == 0){
		clearInterval( this.timer );
		this.timer = null;
		if(this.minimized)  // if back from minification - load immediatly. 
			lightning.load();
		else
			setTimeout("lightning.wait_and_load()", 1500);
		return true;
	}
	return false;

}

// Deal state has just been updated to something.  Handle the different states.
//Available, PromotionSoldOut, ComingSoon
Lightning.prototype.handle_deal_state = function( ){

	if(this.deal_state == "Available"){
		$(".front #claimed").html( Math.round(this.percentage_sold) + "% claimed");
		this.timer_suffix = ' remain';
		
		if( this.timer == null ){
			lightning.update_timer();
			this.timer =  setInterval("lightning.update_timer();", this.timer_interval);
		}
	}
	else if (this.deal_state == "Sold Out" || this.deal_state == "Expired"){
		
		if( this.deal_state == "Expired")
			$(".front #claimed").html( "Expired");
		else
			$(".front #claimed").html( "Sold Out");
		
		// stop updating claimed.
		clearInterval(this.claimed_timer);
		this.claimed_timer = null;
		
		this.timer_suffix = ' to next deal';
		if( this.timer == null )
			this.timer =  setInterval("lightning.update_timer();", this.timer_interval);
		
		$(".front .lightning_line").addClass("gray_out");
		
	}

}